﻿using MES_SystemUI.Helpers;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.Entity.Core.Metadata.Edm;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MES_SystemUI.UI
{
    public partial class Login : Form
    {
        // 全局登录用户字段 LoginUser
        string str = string.Empty;
        public Login()
        {
            InitializeComponent();
            //this.Load += Login_Load;
            this.StartPosition = FormStartPosition.CenterScreen;
            buttonOK.Click += ButtonOK_Click;
            GetStringImage();
            pictureBox1.Click += PictureBox1_Click;
            toolTip1.SetToolTip(pictureBox1, "单击刷新");
            toolTip1.SetToolTip(textBox3, "用户名/手机号");
            try
            {
                textBox3.Text = ConfigurationManager.AppSettings["user"];
                textBox2.Text = EncryptionAndDecryption.Decrypt(ConfigurationManager.AppSettings["password"], SystemDataConfig.KeyStr, SystemDataConfig.IVStr);
            }
            catch
            {
            }
        }

        private void Login_Load(object sender, EventArgs e)
        {
            Task.Run(new Action(() => { 
                using(var c = new Context.MES_SystemContext())
                {
                    var user = c.users;
                }
            }));
        }

        // 验证码 刷新
        private void GetStringImage()
        {
            str = MES_SystemUI.Helpers.VerifyCode.GetVerifyString(6,false);
            pictureBox1.Image = MES_SystemUI.Helpers.VerifyCode.GetVerifyImage(str, pictureBox1.Width, pictureBox1.Height);
            textBox1.Text = str;
        }

        private async void ButtonOK_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(textBox3.Text.Trim()) || string.IsNullOrEmpty(textBox2.Text.Trim()) || string.IsNullOrEmpty(textBox1.Text.Trim()))
            {
                return;
            }
            buttonOK.Enabled = false;
            PictureBox pictureBox = new PictureBox();
            pictureBox.Size = new Size(400,200);
            pictureBox.Location = new System.Drawing.Point(panel1.Width / 2 - pictureBox.Width / 2, panel1.Height / 2 - pictureBox.Height / 2);
            pictureBox.BackColor = System.Drawing.Color.FromArgb(140,70,70,70);
            pictureBox.BorderStyle = BorderStyle.FixedSingle;
            panel1.Controls.Add(pictureBox);
            pictureBox.BringToFront();
            pictureBox.Visible = true;
            CancellationTokenSource cts = new CancellationTokenSource();
            Task task = new Task(new Action(() => {
                int i = 1;
                double r = 75D; //大圆 半径
                int JD = -90;   //初始角度
                Point O = new Point(125, 125); //圆心坐标
                Point Wxy = new Point(125, 50); // 外侧圆 初始坐标
                Size size = new Size(50, 50);   // 所遇员的大小
                int nj = 0; //初始 内圆 扇形 角度
                int statnj = -90;   // 内圆起始角度
                int wj = 180;   // 初始 外圆 扇形 角度
                int statwj = -90;   //  外圆起始角度
                Bitmap bitmaps = new Bitmap(300, 300);  // 画布大小
                Color color = Color.Black;  // 画笔颜色
                bool flag = false;  // 更换画笔颜色关键
                while (!cts.IsCancellationRequested)
                {
                    Graphics g = Graphics.FromImage(bitmaps);
                    g.SmoothingMode = SmoothingMode.HighQuality;
                    g.CompositingQuality = CompositingQuality.HighQuality;
                    g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    g.CompositingMode = CompositingMode.SourceCopy;
                    //g.DrawRectangle(new Pen(color, 1F), new Rectangle(0, 0, 299, 299));
                    GraphicsPath path = new GraphicsPath();
                    // 外环
                    path.StartFigure();
                    //path.AddEllipse(new RectangleF(125, 50, 50, 50));
                    path.AddPie(new Rectangle(Wxy, size), statwj, wj);
                    path.CloseFigure();
                    g.FillPath(new SolidBrush(color), path);

                    path.ClearMarkers();

                    // 内环
                    path.StartFigure();
                    //path.AddEllipse(new RectangleF(125,125,50,50));
                    path.AddPie(new Rectangle(O, size), statnj, nj);
                    path.CloseFigure();
                    g.FillPath(new SolidBrush(color), path);
                    path.Dispose();

                    Bitmap bitmap = new Bitmap(pictureBox.Width, pictureBox.Height);
                    Graphics g1 = Graphics.FromImage(bitmap);
                    g1.DrawImage(bitmaps,new Rectangle(new Point(150,50),new Size(100,100)),new Rectangle(new Point(0,0), new Size(300,300)),GraphicsUnit.Pixel);
                    try
                    {
                        Invoke(new Action(() => {
                            pictureBox.Image = bitmap;
                        }));
                    }
                    catch
                    {
                    }
                    // 如果 为奇数
                    if (i % 2 == 0)
                    {
                        wj = 360;
                    }
                    else // 偶数 改变下面 参数
                    {
                        nj += 45;
                        wj = -180;

                        statwj = 45 * ((i + 1) / 2) - 90;

                        JD = -90 + (45 * ((i + 1) / 2));
                        // 圆上坐标公式 ：x轴坐标 = 圆心x轴坐标+ 半径 * cos（角度）
                        // 圆上坐标公式 ：y轴坐标 = 圆心y轴坐标+ 半径 * sin（角度）
                        double rx = r * Math.Cos((Math.PI / 180) * JD); // Math.Cos() 参数：弧度 ，角度转弧度：弧度 = Math.PI / 180*角度
                        double ry = r * Math.Sin((Math.PI / 180) * JD);
                        Wxy.X = O.X + (int)rx;
                        Wxy.Y = O.Y + (int)ry;
                    }
                    i++;
                    // 重置 参数
                    if (i > 16)
                    {
                        i = 1;
                        r = 75D;
                        JD = -90;
                        O = new Point(125, 125);
                        Wxy = new Point(125, 50);
                        size = new Size(50, 50);
                        nj = 0;
                        statnj = -90;
                        wj = 180;
                        statwj = -90;
                        //bitmaps = new Bitmap(300, 300);
                        // 更换画笔颜色
                        flag = !flag;
                        if (flag)
                        {
                            color = System.Drawing.Color.FromArgb(0, 70, 70, 70);
                        }
                        else
                        {
                            color = Color.Black;
                            //bitmaps = new Bitmap(300, 300);
                        }
                    }
                    // 调整 速度
                    Thread.Sleep(50);
                }
            }), cts.Token);
            task.Start();
            // 解决登录时窗体假死
            if (await LoginIfOnElseAsync()) {
                cts.Cancel();
                this.Close();
            }
            pictureBox.Visible = false;
            cts.Cancel();
            pictureBox.Dispose();
            buttonOK.Enabled = true;
        }

        private async Task<bool> LoginIfOnElseAsync()
        {
            string userName = textBox3.Text;
            string password = textBox2.Text;
            string userStr = textBox1.Text;
            await Task.Run(() => {
                using (var ct = new Context.MES_SystemContext())
                {
                    var reque = from U in ct.users
                                select U;
                    string passE = EncryptionAndDecryption.Encrypt(password, SystemDataConfig.KeyStr, SystemDataConfig.IVStr);
                    //MessageBox.Show(reque.Where(x=>x.UserName==textBox3.Text).Where(x=>x.Password== passE).Count().ToString());
                    //MessageBox.Show(reque.Where(x=>x.Phone==textBox3.Text).Where(x=>x.Password== passE).Count().ToString());
                    if (reque.Where(x => x.UserName == userName).Where(x => x.Password == passE).Count() == 1 || reque.Where(x => x.Phone == userName).Where(x => x.Password == passE).Count() == 1)
                    {
                        if (str != userStr)
                        {
                            Invoke(new Action(() => {
                                MessageBox.Show("验证码错误");
                                GetStringImage();
                            }));
                            return false;
                        }
                        DialogResult = DialogResult.OK;
                        if (reque.Where(x => x.UserName == userName).Where(x => x.Password == passE).Count() == 1)
                        {
                            SystemDataConfig.LoginUser = reque.Where(x => x.UserName == userName).Where(x => x.Password == passE).ToList()[0];
                        }
                        else
                        {
                            SystemDataConfig.LoginUser = reque.Where(x => x.Phone == userName).Where(x => x.Password == passE).ToList()[0];
                        }
                        // 更改 添加app.config
                        Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                        configuration.AppSettings.Settings.Remove("user");
                        configuration.AppSettings.Settings.Remove("password");
                        configuration.AppSettings.Settings.Add("user", userName);
                        configuration.AppSettings.Settings.Add("password", passE);
                        configuration.Save(ConfigurationSaveMode.Modified);
                        return true;
                    }
                    else
                    {
                        Invoke(new Action(() => {
                            MessageBox.Show("账号或密码错误错误");
                            GetStringImage();
                        }));
                        return false;
                    }
                }
            });
            return false;
        }

        private void PictureBox1_Click(object sender, EventArgs e)
        {
            GetStringImage();
        }

        
    }
}
